package com.abel.bigwater.tlv.model

import com.alibaba.fastjson.serializer.JSONSerializer
import com.alibaba.fastjson.serializer.ObjectSerializer
import java.lang.reflect.Type

open class TlvException : Exception {
    constructor() {}
    constructor(message: String) : super(message) {}
    constructor(message: String, cause: Throwable) : super(message, cause) {}
}

/**
 * only in-complete packet can throw this exception!
 */
class TlvNotEnoughByteException : TlvException {
    constructor() {}
    constructor(message: String) : super(message) {}
    constructor(message: String, cause: Throwable) : super(message, cause) {}
}

class TlvUnkownTagException : TlvException {
    constructor() {}
    constructor(message: String) : super(message) {}
    constructor(message: String, cause: Throwable) : super(message, cause) {}
}

class TlvInvalidException : TlvException {
    constructor() {}
    constructor(message: String) : super(message) {}
    constructor(message: String, cause: Throwable) : super(message, cause) {}
}

class TlvExceptionSerializer : ObjectSerializer {
    /**
     * fastjson invokes this call-back method during serialization when it encounters a field of the
     * specified type.
     * @param serializer
     * @param object src the object that needs to be converted to Json.
     * @param fieldName parent object field name
     * @param fieldType parent object field type
     * @param features parent object field serializer features
     * @throws IOException
     */
    override fun write(serializer: JSONSerializer?, `object`: Any?, fieldName: Any?, fieldType: Type?, features: Int) {
        serializer?.out?.write((`object` as TlvException)?.message)
    }
}

class ByteArrayHexSerializer : ObjectSerializer {
    /**
     * fastjson invokes this call-back method during serialization when it encounters a field of the
     * specified type.
     * @param serializer
     * @param object src the object that needs to be converted to Json.
     * @param fieldName parent object field name
     * @param fieldType parent object field type
     * @param features parent object field serializer features
     * @throws IOException
     */
    override fun write(serializer: JSONSerializer?, `object`: Any?, fieldName: Any?, fieldType: Type?, features: Int) {
        serializer?.out?.write(TlvHelper.toHexString(`object` as ByteArray))
    }

}


